package com.hanbang.chu_xing_gao_zhao.view_dynamic;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicBodyData;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicData;
import com.hanbang.chu_xing_gao_zhao.entity.DynamicHorozontalListviewData;
import com.hanbang.chu_xing_gao_zhao.myview.GridViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.chu_xing_gao_zhao.view_public.DynamicCommentActivity;
import com.hanbang.cxgz_2.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 动态正文
 *
 * @author yang
 */
public class DynamicBodyActivity extends BaseActivity {
    /**
     * gridView
     */
    private GridViewForScrollView gridView;

    /**
     * 好友回复listView
     */
    private PullToRefreshListView listView;

    /**
     * 好友回复 的
     */
    private ArrayList<DynamicBodyData> listData;

    /**
     * listData的适配器
     */
    private ListViewAdapter adapter;

    /**
     * 图片展示集合
     */
    private ArrayList<DynamicHorozontalListviewData> hListData;

    /**
     * user对象
     */
    private DynamicData user;

    /**
     * 转发
     */
    private LinearLayout transmit;

    /**
     * 筛选条件
     */
    private int feed_id = 1;

    /**
     * 第几页
     */
    private int pageIndex = 1;

    /**
     * 第页多少条
     */
    private int pageSize = 10;

    /**
     * listView header
     */
    private View headerView;

    private ImageView imageId;
    private ImageView vip;
    private TextView name;
    private TextView time;
    private TextView phone;
    private TextView group;
    private TextView describe;
    private TextView addressed;
    private TextView comment;
    private TextView praise;// 赞
    private TextView share;// 分享

    /**
     * 动态列表list的位置
     */
    private String listPosition = "";
    private Intent intent;

    /**
     * 关注朋友
     */
    private ImageView attentionFriend;
    private TextView attentionFriendText;

    /**
     * 请求的参数
     */
    private RequestParams params = new RequestParams();

    /**
     * 接收广播
     */
    private MyBroadcast myBroadcast;
    /**
     * 广播过滤器
     */
    private IntentFilter intentFilter;
    /**
     * 本地广播管理
     */
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dynamic_body);

        initView();
        getHttpData(imageId, HttpInterfaces.GetFeedCommentList, params, 0);
        setOnClickListener();
        addAdapter();
        addData();
    }

    /**
     * 初始化view
     */
    private void initView() {
        headerView = getLayoutInflater().inflate(R.layout.item_dynamic_listview, null);
        user = new DynamicData();

        transmit = (LinearLayout) headerView.findViewById(R.id.ll_item_dynamic_listview_transmit);
        imageId = (ImageView) headerView.findViewById(R.id.im_item_listview_dynamic_imageId);
        vip = (ImageView) headerView.findViewById(R.id.iv_item_dynamic_listview_vip);
        name = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_name);
        time = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_time);
        phone = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_phone);
        group = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_group);
        describe = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_describe);
        addressed = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_addressed);
        comment = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_comment);
        praise = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_praise);
        share = (TextView) headerView.findViewById(R.id.tv_item_listview_dynamic_share);
        attentionFriend = (ImageView) headerView.findViewById(R.id.cb_item_dynamic_listView_attention);
        attentionFriendText = (TextView) headerView.findViewById(R.id.tv_item_dynamic_listView_attention_text);
        gridView = (GridViewForScrollView) headerView.findViewById(R.id.item_dynamic_gridView);
        hListData = new ArrayList<DynamicHorozontalListviewData>();

        listView = (PullToRefreshListView) findViewById(R.id.lv_dynamic_body_list);
        listData = new ArrayList<DynamicBodyData>();

        /**
         * 接收intent 传递过来的序列化对象
         */
        intent = getIntent();
        hListData = (ArrayList<DynamicHorozontalListviewData>) intent.getSerializableExtra("imageId");
        user = (DynamicData) intent.getSerializableExtra("data");
        feed_id = user.getId();
        listPosition = intent.getStringExtra("listPosition");

        /**
         * 请求参数
         */
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));

        params.addBodyParameter("pageIndex", pageIndex + "");
        params.addBodyParameter("pageSize", pageSize + "");
        params.addBodyParameter("feed_id", feed_id + "");

        /**
         * 注册广播
         */
        myBroadcast = new MyBroadcast();
        intentFilter = new IntentFilter();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        intentFilter.addAction(com.hanbang.chu_xing_gao_zhao.application.Global.BODY_COMMENT);
        localBroadcastManager.registerReceiver(myBroadcast, intentFilter);

    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        transmit.setOnClickListener(onClickListener);
        attentionFriend.setOnClickListener(onClickListener);
        // 评论添加监听
        ((LinearLayout) headerView.findViewById(R.id.ll_item_dynamic_listview_comment))
                .setOnClickListener(onClickListener);
        // 点赞添加监听
        ((LinearLayout) headerView.findViewById(R.id.ll_item_dynamic_listview_likecount))
                .setOnClickListener(onClickListener);

        // 动态列表上下刷新
        listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                listData.clear();

                pageIndex = 1;
                params.addBodyParameter("pageIndex", pageIndex + "");
                getHttpData(imageId, HttpInterfaces.GetFeedCommentList, params, 0);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                ++pageIndex;
                RequestParams params3 = new RequestParams();
                params3.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                params3.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));

                params3.addBodyParameter("pageIndex", pageIndex + "");
                params3.addBodyParameter("pageSize", pageSize + "");
                params3.addBodyParameter("feed_id", feed_id + "");

                getHttpData(imageId, HttpInterfaces.GetFeedCommentList, params3, 0);

            }
        });

        /**
         * 分享的回调
         */
        oks.setCallback(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {

                RequestParams params = new RequestParams();
                params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                        DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));
                params.addBodyParameter("feed_id", feed_id + "");

                getHttpData(share, HttpInterfaces.Feed_Share, params, 0);

            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });

    }

    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                // 分享
                case R.id.ll_item_dynamic_listview_transmit:
                    showShare(DynamicBodyActivity.this);
                    break;

                // 评论
                case R.id.ll_item_dynamic_listview_comment:
                    intent.setClass(DynamicBodyActivity.this, DynamicCommentActivity.class);
                    intent.putExtra("feed_id", user.getId() + "");
                    intent.putExtra("position", listPosition);
                    startActivityForResult(intent, 800);
                    break;

                // 点赞
                case R.id.ll_item_dynamic_listview_likecount:
                    RequestParams params2 = new RequestParams();
                    params2.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                    params2.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));
                    params2.addBodyParameter("feed_id", feed_id + "");
                    getHttpData(comment, HttpInterfaces.Feed_like, params2, 0);

                    break;
                // 关注
                case R.id.cb_item_dynamic_listView_attention:
                    RequestParams params3 = new RequestParams();
                    params3.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                    params3.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));

                    params3.addBodyParameter("user_id", +user.getUid() + "");
                    getHttpData(attentionFriend, HttpInterfaces.Follow, params3, 0);

                    break;

                default:
                    break;
            }
        }
    };

    /**
     * activity 返回的回调
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 800 && resultCode == RESULT_OK) {
            RequestParams params2 = new RequestParams();
            params2.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                    DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
            params2.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                    DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));
            params2.addBodyParameter("text", data.getStringExtra("commentText"));
            params2.addBodyParameter("feed_id", feed_id + "");

            getHttpData(comment, HttpInterfaces.Feed_comment, params2, 0);

            adapter.notifyDataSetChanged();

        }

    }

    ;

    /**
     * 头部添加数据
     */
    private void addData() {
        // 加载网络图片
        bitmapUtils.display(imageId, SystemTools.getHttpFileUrl(user.getAvatar()));
        name.setText(user.getUser_name());

        // 显示日期
        time.setText(StringUtils_2.getTime(user.getAdd_time()));

        phone.setText(user.getPhone());
        group.setText(String.valueOf(user.getFriendcount()));

        StringBuffer sb = new StringBuffer();
        // 把表情转义显示
        if (user.getText() != null) {
            sb.append(user.getText().toString());

            describe.setText(ImageStringUtils.getEmotionContent(DynamicBodyActivity.this, describe, sb.toString()));

            sb.delete(0, sb.length());
        }
        // 指定一个特殊字符，截取它后面的内容。（服务器返回过来的日期为：**省-**市-**区-**街道），显示时只显示街道。
        String symbol = "-";
        addressed.setText(StringUtils_2.getText(user.getPosition(), symbol));
        share.setText(String.valueOf(user.getSharecount()));
        comment.setText(String.valueOf(user.getCommentcount()));
        praise.setText(String.valueOf(user.getLikecount()));
        if (!user.isIs_vip()) {

            vip.setVisibility(View.GONE);
        }

        if (user.getFollow() == 0) {

            attentionFriendText.setText("已关注");
            attentionFriend.setSelected(true);

        } else {
            attentionFriendText.setText("已关注");
            attentionFriend.setSelected(true);
        }
    }

    /**
     * 为水平的listivew 添加adapter
     */
    private void addAdapter() {

        gridView.setAdapter(new GridViewAdapter(hListData));

        adapter = new ListViewAdapter(listData);

        listView.setMode(Mode.BOTH);
        // 设置一个头布局
        AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                AbsListView.LayoutParams.WRAP_CONTENT);
        headerView.setLayoutParams(layoutParams);
        // 把listView转换成正常的listView,时行添加头部
        ListView lv = listView.getRefreshableView();
        lv.addHeaderView(headerView);
        listView.setAdapter(adapter);

    }

    @Override
    protected void onResume() {
        setTitleMore(View.VISIBLE, View.VISIBLE, "动态正文", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        localBroadcastManager.unregisterReceiver(myBroadcast);

        super.onDestroy();
    }

    /**
     * gridview adapter
     *
     * @author Administrator
     */
    class GridViewAdapter extends BaseAdapter {
        public ArrayList<DynamicHorozontalListviewData> list;

        public GridViewAdapter(ArrayList<DynamicHorozontalListviewData> list) {

            if (list != null) {
                this.list = list;
            } else {
                list = new ArrayList<DynamicHorozontalListviewData>();
            }
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public DynamicHorozontalListviewData getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            UiUtils.applyFont(convertView);
            ViewHolder viewHolder;

            if (convertView == null) {// 是空加载
                convertView = getLayoutInflater().inflate(R.layout.item_dycamic_horizontal_listview, null);

                viewHolder = new ViewHolder();

                viewHolder.goodsImage = (ImageView) convertView.findViewById(R.id.iv_item_shoppingcart_recommend_image);

                convertView.setTag(viewHolder);
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            DynamicHorozontalListviewData data = getItem(position);

            bitmapUtils.display(viewHolder.goodsImage, SystemTools.getHttpFileUrl(data.getImg_url()));

            /**
             * 点击图片查看详情
             */
            viewHolder.goodsImage.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(DynamicBodyActivity.this, PhotoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("listdata", list);
                    intent.putExtras(bundle);
                    intent.putExtra("position", position);
                    startActivity(intent);

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            private ImageView goodsImage; // 产品图片

        }

    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ListViewAdapter extends BaseAdapter {

        public ArrayList<DynamicBodyData> list = new ArrayList<DynamicBodyData>();

        public ListViewAdapter(ArrayList<DynamicBodyData> listData) {
            this.list = listData;
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public DynamicBodyData getItem(int position) {

            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            final ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                convertView = getLayoutInflater().inflate(R.layout.item_dynamic_body, null);
                UiUtils.applyFont(convertView);
                viewHolder = new ViewHolder();

                // 子控件初始化
                viewHolder.portraitId = (ImageView) convertView.findViewById(R.id.item_dynamic_body_portrit);
                viewHolder.describe = (TextView) convertView.findViewById(R.id.item_dynamic_body_describe);
                viewHolder.date = (TextView) convertView.findViewById(R.id.item_dynamic_body_date);
                viewHolder.replyName = (TextView) convertView.findViewById(R.id.item_dynamic_body_replyName);
                viewHolder.replyCurrent = (TextView) convertView.findViewById(R.id.item_dynamic_body_replyCurrent);
                viewHolder.praise = (TextView) convertView.findViewById(R.id.item_dynamic_body_praise);
                viewHolder.llPraise = (LinearLayout) convertView.findViewById(R.id.ll_item_dynamic_body_praise);

                convertView.setTag(viewHolder);// 把现有有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            final DynamicBodyData data = getItem(position);

            bitmapUtils.display(viewHolder.portraitId, SystemTools.getHttpFileUrl(data.getAvatar()));

            viewHolder.describe.setText(data.getText());
            viewHolder.date.setText(StringUtils_2.getTime(data.getAdd_time()));
            viewHolder.replyName.setText(data.getUser_name());
            viewHolder.praise.setText(data.getLikecount() + "");

            /**
             * 头像点击跳转
             */
            viewHolder.portraitId.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                }
            });

            /**
             * 赞的监听
             * */
            viewHolder.llPraise.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    RequestParams params2 = new RequestParams();
                    params2.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
                    params2.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                            DynamicBodyActivity.this, MySharedPreferences.USER_DATA, "password"));
                    params2.addBodyParameter("comment_id", data.getId() + "");

                    getHttpData(viewHolder.praise, HttpInterfaces.FeedCommentLike, params2, position);

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            // 子控件主要是里面的数据
            private ImageView portraitId;// 肖像图片
            private TextView describe;// 描述
            private TextView date;// 日期
            private TextView replyName;// 回复
            private TextView replyCurrent;// 回复内容
            private TextView praise;// 赞
            private LinearLayout llPraise;// 赞

        }

    }

    /**
     * 获取动态列表
     */
    private void getHttpData(final View v, String url, RequestParams params, final int position) {

        httpUtils.send(HttpMethod.POST, url, params, new MyRequestCallBack<String>(this, "页面加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {

                    JSONObject json = new JSONObject(responseInfo.result);

                    int result = json.getInt("Result");
                    String msg = json.getString("Msg");

                    if (result == 0) {

                        // 关注
                        if (v.getId() == R.id.cb_item_dynamic_listView_attention) {

                            ((TextView) findViewById(R.id.tv_item_dynamic_listView_attention_text)).setText("已关注");
                            v.setSelected(true);

                        }

                        // 评论
                        if (v.getId() == R.id.tv_item_listview_dynamic_comment) {

                            comment.setText(Integer.parseInt(comment.getText().toString()) + 1 + "");
                            // 发送一条本地广播，提醒从新调用接口
                            Intent intent = new Intent(com.hanbang.chu_xing_gao_zhao.application.Global.BODY_COMMENT);
                            localBroadcastManager.sendBroadcast(intent);

                            return;
                        }
                        // 点赞
                        if (v.getId() == R.id.ll_item_dynamic_listview_likecount) {

                            praise.setText(Integer.parseInt(praise.getText().toString()) + 1 + "");
                            return;
                        }

                        // 分享
                        if (v.getId() == R.id.tv_item_listview_dynamic_share) {

                            share.setText(Integer.parseInt(share.getText().toString()) + 1 + "");
                            return;
                        }

                        // 评论的点赞
                        if (v.getId() == R.id.item_dynamic_body_praise) {
                            listData.get(position).setLikecount(listData.get(position).getLikecount() + 1);
                            adapter.notifyDataSetChanged();
                            return;
                        }

                        JSONArray VArray = json.getJSONArray("list");
                        // 如果是空表示是最后页
                        if (VArray.length() == 0) {
                            if (pageIndex == 1) {
                                MyToast.show(DynamicBodyActivity.this, "暂无评论", 1);
                                return;
                            }
                            MyToast.show(DynamicBodyActivity.this, "没有更多评论", 1);

                            // 停止刷新
                            listView.onRefreshComplete();
                            return;
                        }

                        // 把数据从接口解析出来
                        listData.addAll(JsonHelper.parseCollection(VArray, ArrayList.class, DynamicBodyData.class));
                        adapter.notifyDataSetChanged();

                    } else {
                        MyToast.show(DynamicBodyActivity.this, msg, 1);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 停止刷新
                listView.onRefreshComplete();
            }
        });

    }

    /**
     * 广播接收,收到 后更新评论列表
     *
     * @author yang
     */
    class MyBroadcast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            // 接到广播 ,把集合清空，从新调用接口
            listData.clear();
            hListData.clear();
            pageIndex = 1;
            getHttpData(imageId, HttpInterfaces.GetFeedCommentList, params, 0);

        }

    }

}
